import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;



public class TestSocket extends AbstractJavaSamplerClient {
	private String serverIp;
    private int serverPort;
    private String file;
    
    public SampleResult runTest(JavaSamplerContext sc){
        serverIp=sc.getParameter("serverIp");
        serverPort=Integer.valueOf(sc.getParameter("serverPort"));
        file=sc.getParameter("file");
        
        System.out.println("Host:"+serverIp + "Port:" + serverPort + "File:" + file);
        
        String message=readFileByLines(file);
        
        SampleResult sr=new SampleResult();
        sr.setSampleLabel("Socket Test");
        try{
            
            JSocketClient c=new JSocketClient();
            c.callServer(serverIp,serverPort,message);
        }catch(Exception e){
            e.printStackTrace();
            sr.setSuccessful(false);
        }finally{
            sr.sampleEnd();
        }
        return sr;
    }
    
    public Arguments getDefaultParameters(){
        Arguments params=new Arguments();
        params.addArgument("serverIp","10.13.0.88");
        params.addArgument("serverPort","7001");
        params.addArgument("file","F:/test.txt");
        return params;
    }
    
    public void setupTest(JavaSamplerContext context){
        super.setupTest(context);
    }
    
    public void teardownTest(JavaSamplerContext context){
        super.teardownTest(context);
    }
    
    private String readFileByLines(String fileName){
        File file=new File(fileName);
        BufferedReader reader=null;
        StringBuffer sb=new StringBuffer();
        try{
            //System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader=new BufferedReader(new FileReader(file));
            String tempString=null;
            //int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while((tempString=reader.readLine())!=null){
                // 显示行号
                sb=sb.append(tempString);
                //System.out.println("line " + line + ": " + tempString);
                //line++;
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader!=null){
                try{
                    reader.close();
                }catch(IOException e1){
                }
            }
        }
        
        return sb.toString();
    }

}
